# -*- coding: utf-8 -*-

import os
import logging

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_wtf.csrf import CSRFProtect
from werkzeug.utils import import_string

from config import config
from mpdev.gzone_loader import GzoneLoader
from mpdev.wechat import WeChat
from mpdev.serializer import Serializer
from mpdev.redis_interface import RedisInterface
from mpdev.logger import Logger

BASE_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

db = SQLAlchemy()
csrf = CSRFProtect()
gzone_loader = GzoneLoader()
wechat = WeChat()
serializer = Serializer()
redis_interface = RedisInterface()
app_logger = Logger()

# todo: 与wxservice集成,读取配置信息


def create_app(config_name=None):
    app = Flask(__name__)

    if config_name is not None:
        app.config.from_object(config[config_name])

    app.config.setdefault('LOCAL_TEST', False)
    app.config.setdefault('SKIP_OAUTH2', False)
    app.base_path = BASE_PATH

    db.init_app(app)
    csrf.init_app(app)
    gzone_loader.init_app(app)
    wechat.init_app(app)
    serializer.init_app(app)
    redis_interface.init_app(app)
    # should be placed before bp module importing
    app_logger.init_app(app)

    installed_blueprints = app.config.get('INSTALLED_BLUEPRINTS', [])
    for bp in installed_blueprints:
        bp = import_string(bp)
        app.register_blueprint(bp)

    return app
